package com.ldzg.blockwatcher.watcher.tron;

import cn.hutool.json.JSONObject;
import com.ldzg.blockwatcher.config.tron.TronProperties;
import com.ldzg.blockwatcher.notify.enums.NotifySourceEnum;
import com.ldzg.blockwatcher.risk.RiskEngine;
import com.ldzg.blockwatcher.risk.dto.TransactionInfo;
import com.ldzg.blockwatcher.utils.ThreadPoolUtil;
import com.ldzg.blockwatcher.watcher.AbstractWatcher;
import com.ldzg.blockwatcher.watcher.tron.dto.TronTransactionDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *  波厂链 监听交易
 *
 * @author: 18310740596@163.com
 * @date: 2025-07-05 10:55:18
 * @version: v1.0
 * @describe: class responsibility
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TronAlarmWatcher extends AbstractWatcher {

    private final RiskEngine riskEngine;

    private final TronProperties tronProperties;

    private static final int MAX_CAPACITY = 2048;

    public static final BlockingQueue<TronTransactionDTO> DATA_QUEUE = new LinkedBlockingQueue<>(MAX_CAPACITY);

    private final AtomicBoolean running = new AtomicBoolean(Boolean.TRUE);

    @Override
    public void watcher() {
        log.info("波厂连 - 实时建议监听");
        while (running.get()) {
            try {
                TronTransactionDTO transaction = DATA_QUEUE.take();
                // 处理交易
                ThreadPoolUtil.execute(() -> watcherHandle(transaction));
            } catch (InterruptedException ignore) {}
        }
    }


    private void watcherHandle(TronTransactionDTO data) {
        // 此处数据量可能比较大, 可将数据放入MQ进行处理

        TransactionInfo transactionInfo = TransactionInfo.builder()
                                          .source(NotifySourceEnum.TRON)
                                          .txHash(data.getTransactionId())
                                          .fromAddress(data.getResult().getFrom())
                                          .toAddress(data.getResult().getTo())
                                          .amount(new BigInteger(data.getResult().getAmount()))
                                          .concatAddress(tronProperties.getUsdtContract())
                                          .raw(data)
                                          .build();
        // 风控检测
        riskEngine.check(transactionInfo);
    }


    @Override
    public void dispose() {
        running.set(Boolean.FALSE);
    }
}
